package com.ferryc.modules.sys.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ferryc.commons.csrf.CookieCsrfTokenRepository;
import com.ferryc.commons.utils.DigestUtil;
import com.ferryc.commons.utils.StringUtil;
import com.ferryc.commons.utils.WebUtil;
import com.ferryc.commons.web.BaseController;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.constant.ResultConstant;
import com.ferryc.modules.sys.entity.SysUser;
import com.ferryc.modules.sys.entity.param.SysUserParam;
import com.ferryc.modules.sys.entity.param.UserPassdParam;
import com.ferryc.modules.sys.service.ISysUserService;

/**
 * 
 * 类名: SysUsersController <br/>
 * 作用： 控制<br/>
 * 方法： <br/>
 * 创建者: Ferry C <br/>
 * 添加时间: 2017年12月04日 10:14:23 <br/>
 */
@Controller
@RequestMapping("/user")
public class SysUserController extends BaseController {

	/** */
	@Autowired
	private ISysUserService sysUsersService;

	/** */
	@RequiresPermissions("user")
	@GetMapping("/")
	public String manage(Model model) {
		return "sys/user/list";
	}

	/**
	 * 列表查询
	 * 
	 * @param sysUsersParam
	 *            请求参数
	 * @return
	 */
	@RequiresPermissions("user")
	@PostMapping("/list")
	@ResponseBody
	public Object list(SysUserParam sysUsersParam) {
		sysUsersParam.setStatus(StringUtil.EMPTY);
		return sysUsersService.selectPage(sysUsersParam.toSysUsers());
	}

	/**
	 * 进入新增页面
	 * 
	 * @param sysLogInfoParam
	 *            请求参数
	 * @param model
	 *            Model
	 * @param request
	 *            request
	 * @return
	 */
	@RequiresPermissions("user_add")
	@GetMapping("/addPage")
	public Object addPage(SysUserParam sysUsersParam, Model model, HttpServletRequest request) {
		model.addAttribute(GlobalConstant.PARENT_ID, request.getParameter(GlobalConstant.PARENT_ID));
		return "sys/user/add";
	}

	/**
	 * 新增保存
	 * 
	 * @param sysUsersParam
	 *            请求参数
	 * @param bindingResult
	 *            数据校验结果
	 * @return
	 */
	@RequiresPermissions("user_add")
	@PostMapping("/insert")
	@ResponseBody
	public Object insert(@Valid SysUserParam sysUsersParam, BindingResult bindingResult, HttpServletRequest request) {
		if (bindingResult.hasErrors()) {
			List<FieldError> errorList = bindingResult.getFieldErrors();
			return renderError(errorList);
		}
		boolean flag = sysUsersService.cheakUserLoginName(sysUsersParam.toSysUsers());
		if (!flag) {
			return renderError(ResultConstant.EXISTS_LOGIN_NAME);
		}
		String pwd = DigestUtil.decrypt3Des(sysUsersParam.getPassword(), WebUtil.getCookieValue(request, CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME).replaceAll("-", ""));
		sysUsersParam.setPassword(pwd);
		sysUsersParam.preInsert();
		sysUsersService.insertSysUser(sysUsersParam.toSysUsers());
		return renderSuccess(ResultConstant.INSERT_SUCCESS);
	}

	/**
	 * 进入查看页面
	 * 
	 * @param sysUsersParam
	 *            请求参数
	 * @param model
	 *            Model
	 * @param request
	 * @return
	 */
	@RequiresPermissions("user_view")
	@GetMapping("/viewPage")
	public Object viewPage(SysUserParam sysUsersParam, Model model, HttpServletRequest request) {
		sysUsersParam.setStatus(StringUtil.EMPTY);
		SysUser sysUsers = sysUsersService.get(sysUsersParam.getId());
		model.addAttribute("info", sysUsers);
		model.addAttribute(GlobalConstant.READ_ONLY, Boolean.TRUE);
		return "sys/user/edit";
	}

	/**
	 * 进入修改页面
	 * 
	 * @param sysUsersParam
	 *            请求参数
	 * @param model
	 *            Model
	 * @param request
	 * @return
	 */
	@RequiresPermissions("user_update")
	@GetMapping("/editPage")
	public Object editPage(SysUserParam sysUsersParam, Model model, HttpServletRequest request) {
		sysUsersParam.setStatus(StringUtil.EMPTY);
		SysUser sysUsers = sysUsersService.get(sysUsersParam.getId());
		model.addAttribute("info", sysUsers);
		model.addAttribute(GlobalConstant.READ_ONLY, Boolean.FALSE);
		return "sys/user/edit";
	}

	/**
	 * 修改
	 * 
	 * @param sysUsersParam
	 *            请求参数
	 * @param bindingResult
	 *            数据校验结果
	 * @return
	 */
	@RequiresPermissions("user_update")
	@PostMapping("/save")
	@ResponseBody
	public Object save(@Valid SysUserParam sysUsersParam, BindingResult bindingResult, HttpServletRequest request) {
		if (bindingResult.hasErrors()) {
			List<FieldError> errorList = bindingResult.getFieldErrors();
			return renderError(errorList);
		}
		boolean flag = sysUsersService.cheakUserLoginName(sysUsersParam.toSysUsers());
		if (!flag) {
			return renderError(ResultConstant.EXISTS_LOGIN_NAME);
		}
		sysUsersParam.setPassword(StringUtil.EMPTY);
		sysUsersParam.preUpdate();
		sysUsersService.updateSysUser(sysUsersParam.toSysUsers());
		return renderSuccess(ResultConstant.UPDATE_SUCCESS);
	}

	/**
	 * 删除
	 * 
	 * @param sysUsersParam
	 *            请求参数
	 * @param bindingResult
	 *            数据校验结果
	 * @return
	 */
	@RequiresPermissions("user_delete")
	@PostMapping("/delete")
	@ResponseBody
	public Object delete(SysUserParam sysUsersParam, BindingResult bindingResult) {
		sysUsersParam.preUpdate();
		sysUsersParam.setDelFlag(GlobalConstant.YES);
		sysUsersService.deleteSysUser(sysUsersParam.toSysUsers());
		return renderSuccess(ResultConstant.DELETE_SUCCESS);
	}

	@RequiresPermissions("user_uppwd")
	@GetMapping("/updatePwd")
	public Object addPage(UserPassdParam userPassdParam, Model model, HttpServletRequest request) {
		String id = userPassdParam.getId();
		if (StringUtil.isBlank(id)) {
			id = getUserId();
		}
		model.addAttribute(GlobalConstant.ID, id);
		return "sys/user/updatePwd";
	}

	/**
	 * 修改密码
	 * 
	 * @param userPassdParam
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequiresPermissions("user_uppwd")
	@PostMapping("/savePwd")
	@ResponseBody
	public Object savePwd(UserPassdParam userPassdParam, BindingResult bindingResult, HttpServletRequest request) {
		if (bindingResult.hasErrors()) {
			List<FieldError> errorList = bindingResult.getFieldErrors();
			return renderError(errorList);
		}
		SysUser sysUser = userPassdParam.toSysUsers();
		String pwd = DigestUtil.decrypt3Des(sysUser.getPassword(), WebUtil.getCookieValue(request, CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME).replaceAll("-", ""));
		sysUser.setPassword(pwd);
		SysUser queryUser = sysUsersService.get(sysUser.getId());
		sysUser.setPassword(DigestUtil.hashByShiro(GlobalConstant.MD5, sysUser.getPassword().toCharArray(), ByteSource.Util.bytes(queryUser.getSalt()), 1));
		sysUser.preUpdate();
		sysUsersService.update(sysUser);
		return renderSuccess(ResultConstant.UPDATE_SUCCESS);
	}
}